package com.lagou.edu.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpStatus;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.lagou.edu.entity.TAuthCode;
import com.lagou.edu.entity.TToken;
import com.lagou.edu.entity.TUser;
import com.lagou.edu.service.ITAuthCodeService;
import com.lagou.edu.service.ITTokenService;
import com.lagou.edu.service.ITUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.http.HTTPBinding;
import java.util.List;

/**
 * @program: springcloud-web-one
 * @description: 用户控制
 * @author: zhoushiduo
 * @create: 2021-03-18 15:23
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ITAuthCodeService itAuthCodeService;

    @Autowired
    private ITTokenService itTokenService;

    @Autowired
    private ITUserService itUserService;

    /**
     * 注册接⼝，0成功，-1,2失败
     * @param email
     * @param password
     * @param code
     * @return
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public int register(@PathVariable("email") String email, @PathVariable("password") String password, @PathVariable("code") String code) {
        //验证码
        QueryWrapper<TAuthCode> tAuthCodeQueryWrapper = new QueryWrapper<>();
        tAuthCodeQueryWrapper.eq("email", email)
                .ge("expiretime", DateUtil.date());
        List<TAuthCode> list = itAuthCodeService.list(tAuthCodeQueryWrapper);
        boolean codeIsExits = false;
        for (TAuthCode tAuthCode : list) {
            if (tAuthCode.getCode().equalsIgnoreCase(code)) {
                codeIsExits = true;
            }
        }
        if (!codeIsExits) {
            return 2;
        }
        //新建注册用户
        TUser tUser = new TUser();
        tUser.setEmail(email);
        tUser.setPassword(SecureUtil.md5(password));
        boolean b = itUserService.saveOrUpdate(tUser);
        if (b) {
            return 0;
        }
        return -1;
    }

    /**
     * 是否已注册，根据邮箱判断,true代表已经注册过，
     *     false代表尚未注册
     * @param email
     * @return
     */
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable("email") String email) {
        QueryWrapper<TUser> tUserServiceWrapper = new QueryWrapper<>();
        tUserServiceWrapper.eq("email", email);
        TUser one = itUserService.getOne(tUserServiceWrapper);
        if (one == null) {
            return false;
        }
        return true;
    }

    /**
     * 邮箱地址
     *     登录接口，验证用户名密码合法性，根据用户名和
     *     密码生成token，token存入数据库，并写入cookie
     *     中，登录成功返回邮箱地址，重定向到欢迎⻚页
     * @param email
     * @param password
     * @return
     */
    @GetMapping("/login/{email}/{password}")
    public Boolean isRegistered(@PathVariable("email") String email, @PathVariable("password") String password, HttpServletResponse resp) {
        QueryWrapper<TUser> tAuthCodeWrapper = new QueryWrapper<>();
        tAuthCodeWrapper.eq("email", email)
                .eq("password", SecureUtil.md5(password));
        TUser one = itUserService.getOne(tAuthCodeWrapper);
        if (one == null) {
            return false;
        }
        String uuid = UUID.fastUUID().toString();
        TToken tToken = new TToken();
        tToken.setEmail(email);
        tToken.setToken(uuid);
        boolean b = itTokenService.saveOrUpdate(tToken);
        if (b) {
            RedirectAttributes redirectAttributes = new RedirectAttributesModelMap();
            redirectAttributes.addFlashAttribute("email", email);
            redirectAttributes.addFlashAttribute("token", uuid);
            //添加cookie
            Cookie cookie = new Cookie("token", uuid);
            cookie.setMaxAge(7*24*60*60);
            cookie.setPath("/");
            resp.addCookie(cookie);
            //跳转
            return true;
        }
        //token失败
        return false;
    }

    /**
     * 邮箱地址 根据token查询用户登录邮箱接口
     * @param token
     * @return
     */
    @GetMapping("/info/{token}")
    public String info(@PathVariable("token") String token) {

        JSONObject jsonObject = new JSONObject();
        QueryWrapper<TToken> tTokenQueryWrapper = new QueryWrapper<>();
        tTokenQueryWrapper.eq("token", token);
        TToken one = itTokenService.getOne(tTokenQueryWrapper);
        if (one == null) {
            return "";
        }
        return one.getEmail();
    }
}
